<?php

namespace paper;


use paper\helper\DotAccessTrait;

class Config implements \ArrayAccess
{
    private static array $configs = [];
    private array $config = [];
    public static string $configBasePath = "";

    use DotAccessTrait;

    public function __construct(array $config)
    {
        $this->config = &$config;
    }

    public static function load($name): self
    {
        if (!isset(self::$configs[$name])) {
            $file = self::$configBasePath . '/' . $name . '.php';
            if (file_exists($file))
                self::$configs[$name] = new self(include($file));
            else
                self::$configs[$name] = new self([]);
        }
        return self::$configs[$name];
    }

    public function get($key, $default = null)
    {
        return $this->dotAccess($key, $this->config, $default);
    }

    public function offsetExists(mixed $offset): bool
    {
        return isset($this->config[$offset]);
    }

    public function offsetGet(mixed $offset)
    {
        return $this->config[$offset];
    }

    public function offsetSet(mixed $offset, mixed $value)
    {
        $this->config[$offset] = $value;
    }

    public function offsetUnset(mixed $offset)
    {
        unset($this->config[$offset]);
    }
}